<template>
  <div>
  <div class="chat-message" :class="messageClass">
    <!-- 用户消息 -->
    <div v-if="message.role === 'user'" class="message-content user-message">
      <div class="message-avatar">
        <el-icon><User /></el-icon>
      </div>
      <div class="message-body">
        <div class="message-header">
          <span class="message-sender">{{ t('aiChat.user') }}</span>
          <span class="message-time">{{ formatTime(message.timestamp) }}</span>
        </div>
        <div class="message-text">
          <MdPreview
            :id="`user-msg-preview-${message.id}`"
            :modelValue="displayContent"
            :theme="'light'"
            language="zh-CN"
            class="md-preview-content"
          />
        </div>
      </div>
    </div>

    <!-- AI消息 -->
    <div v-else class="message-content ai-message">
      <div class="message-avatar">
        <el-icon><ChatLineRound /></el-icon>
      </div>
      <div class="message-body">
        <div class="message-header">
          <span class="message-sender">{{ t('aiChat.assistant') }}</span>
          <span class="message-time">{{ formatTime(message.timestamp) }}</span>
          <div class="message-actions">
            <el-button
              v-if="message.error"
              @click="handleRetry"
              type="primary"
              size="small"
              text
            >
              <el-icon><Refresh /></el-icon>
              {{ t('aiChat.retry') }}
            </el-button>
            <template v-else-if="!streaming && message.content">
              <el-button
                @click="copyMessage"
                type="default"
                size="small"
                text
              >
                <el-icon><DocumentCopy /></el-icon>
                {{ t('aiChat.copy') }}
              </el-button>


            </template>
          </div>
        </div>
        <div class="message-text" :class="{ 'error-message': message.error }">
          <div v-if="message.error" class="error-content">
            <el-icon class="error-icon"><Warning /></el-icon>
            {{ message.content }}
          </div>
          <div v-else class="normal-content">
            <!-- 推理过程展示区域 -->
            <div v-if="hasReasoning || isThinking" class="reasoning-section">
              <div class="reasoning-header" @click="toggleReasoning">
                <div class="reasoning-title">
                  <el-icon class="thinking-icon" :class="{ spinning: isThinking }">
                    <Loading v-if="isThinking" />
                    <ChatDotRound v-else />
                  </el-icon>
                  <span>{{ isThinking ? '深度思考...' : '思考过程' }}</span>
                  <span v-if="!isThinking && hasReasoning && thinkingTimeDisplay" class="reasoning-count">
                    ({{ thinkingTimeDisplay }})
                  </span>
                </div>
                <el-icon
                  v-if="!isThinking && hasReasoning"
                  class="expand-icon"
                  :class="{ expanded: reasoningExpanded }"
                >
                  <ArrowDown />
                </el-icon>
              </div>

              <!-- 推理内容 -->
              <div
                v-if="reasoningExpanded && hasReasoning"
                class="reasoning-content"
              >
                <div class="reasoning-text">
                  {{ displayReasoning }}
                  <span v-if="isThinking" class="thinking-cursor">|</span>
                </div>
                <div v-if="!isThinking" class="reasoning-actions">
                  <el-button
                    @click="copyReasoning"
                    type="default"
                    size="small"
                    text
                  >
                    <el-icon><DocumentCopy /></el-icon>
                    复制思考过程
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 回答内容 -->
            <div class="answer-content">
              <!-- 统一使用 MdPreview 进行 Markdown 渲染，包括流式输入 -->
              <MdPreview
                :id="`ai-msg-preview-${message.id}`"
                :modelValue="displayContent"
                :theme="'light'"
                language="zh-CN"
                class="md-preview-content"
              />

              <!-- 图片显示区域 -->
              <div v-if="hasImages" class="image-gallery">
              <div
                v-for="(imageUrl, index) in extractedImages"
                :key="index"
                class="image-item"
              >
                <!-- 图片状态检测 -->
                <div v-if="isTemporaryImageUrl(imageUrl)" class="image-status-wrapper">
                  <!-- 检查中状态 -->
                  <div v-if="getImageStatus(imageUrl).status === 'loading'" class="image-status checking">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                    <span>检查图片状态...</span>
                  </div>

                  <!-- 图片过期状态 -->
                  <div v-else-if="getImageStatus(imageUrl).status === 'expired'" class="image-status expired">
                    <div class="expired-placeholder">
                      <el-icon class="expired-icon"><Warning /></el-icon>
                      <div class="expired-text">
                        <p>图片链接已过期</p>
                        <p class="expired-hint">AI生成的图片链接具有时效性，建议及时保存</p>
                      </div>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Refresh"
                        @click="retryImage(imageUrl)"
                        class="retry-btn"
                      >
                        重试
                      </el-button>
                    </div>
                  </div>

                  <!-- 图片正常显示 -->
                  <div v-else-if="getImageStatus(imageUrl).status === 'success'">
                    <el-image
                      :src="imageUrl"
                      :alt="`生成的图片 ${index + 1}`"
                      fit="cover"
                      class="generated-image"
                      :preview-src-list="extractedImages.filter(url => getImageStatus(url).status === 'success')"
                      :initial-index="index"
                      loading="lazy"
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                          <span>图片加载失败</span>
                        </div>
                      </template>
                    </el-image>
                  </div>

                  <!-- 检查失败状态 -->
                  <div v-else class="image-status error">
                    <div class="error-placeholder">
                      <el-icon class="error-icon"><Warning /></el-icon>
                      <div class="error-text">
                        <p>图片状态检查失败</p>
                        <p class="error-hint">{{ getImageStatus(imageUrl).error || '未知错误' }}</p>
                      </div>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Refresh"
                        @click="retryImage(imageUrl)"
                        class="retry-btn"
                      >
                        重试
                      </el-button>
                    </div>
                  </div>
                </div>

                <!-- 非临时URL直接显示 -->
                <div v-else>
                  <el-image
                    :src="imageUrl"
                    :alt="`生成的图片 ${index + 1}`"
                    fit="cover"
                    class="generated-image"
                    :preview-src-list="extractedImages"
                    :initial-index="index"
                    loading="lazy"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>图片加载失败</span>
                      </div>
                    </template>
                  </el-image>
                </div>

                <!-- 图片操作按钮 -->
                <div class="image-actions" v-if="!isTemporaryImageUrl(imageUrl) || getImageStatus(imageUrl).status === 'success'">
                  <el-button
                    size="small"
                    :icon="Download"
                    @click="downloadImage(imageUrl, index)"
                    title="下载图片"
                  />
                  <el-button
                    size="small"
                    :icon="DocumentCopy"
                    @click="copyImageUrl(imageUrl)"
                    title="复制链接"
                  />
                </div>
              </div>
              </div>
            </div>

            <!-- AI消息反馈按钮 -->
            <div
              v-if="!streaming && message.content && showFeedback !== false"
              class="message-feedback"
            >
              <div class="feedback-buttons">
                <el-tooltip content="有帮助" placement="top">
                  <el-button
                    :type="feedbackState === 'like' ? 'primary' : 'default'"
                    size="small"
                    text
                    @click="handleFeedback('like')"
                    class="feedback-btn"
                  >
                    <el-icon><CircleCheck /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="没有帮助" placement="top">
                  <el-button
                    :type="feedbackState === 'dislike' ? 'danger' : 'default'"
                    size="small"
                    text
                    @click="handleFeedback('dislike')"
                    class="feedback-btn"
                  >
                    <el-icon><CircleClose /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUpdated, nextTick, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import {
  User,
  ChatLineRound,
  Refresh,
  DocumentCopy,
  Warning,
  Picture,
  Download,
  Loading,
  ChatDotRound,
  ArrowDown,
  CircleCheck,
  CircleClose
} from '@element-plus/icons-vue'
import type { ChatMessage } from '@/types/aiChat'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import 'md-editor-v3/lib/preview.css'
import { imageStatusChecker, isTemporaryImageUrl, type ImageStatus } from '@/utils/imageChecker'

interface Props {
  message: ChatMessage
  streaming?: boolean
  showFeedback?: boolean // 控制是否显示反馈按钮
}

interface Emits {
  (e: 'retry'): void
  (e: 'feedback', type: 'like' | 'dislike', messageId: string): void // 消息反馈
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

// 响应式数据
const reasoningExpanded = ref(true) // 默认展开思考过程
const feedbackState = ref<'like' | 'dislike' | null>(null) // 反馈状态
const thinkingStartTime = ref<number | null>(null) // 思考开始时间
const thinkingDuration = ref<number>(0) // 思考持续时间（秒）

// 计算属性
const messageClass = computed(() => ({
  'user-message-wrapper': props.message.role === 'user',
  'ai-message-wrapper': props.message.role === 'assistant',
  'streaming': props.streaming,
  'error': props.message.error
}))

// 推理相关计算属性
const hasReasoning = computed(() => {
  return props.message.reasoning && props.message.reasoning.trim().length > 0
})

const isThinking = computed(() => {
  return props.streaming && props.message.role === 'assistant' &&
         (props.message.reasoning || '') !== '' && !props.message.content
})

const displayReasoning = computed(() => {
  return props.message.reasoning || ''
})



// 思考时间显示
const thinkingTimeDisplay = computed(() => {
  if (thinkingDuration.value === 0) return ''

  if (thinkingDuration.value < 60) {
    return `${thinkingDuration.value}秒`
  } else {
    const minutes = Math.floor(thinkingDuration.value / 60)
    const seconds = thinkingDuration.value % 60
    return seconds > 0 ? `${minutes}分${seconds}秒` : `${minutes}分钟`
  }
})

// 监听推理内容变化，跟踪思考时间
watch(() => props.message.reasoning, (newReasoning, oldReasoning) => {
  // 开始思考：从无推理内容到有推理内容
  if (!oldReasoning && newReasoning && props.streaming && props.message.role === 'assistant') {
    thinkingStartTime.value = Date.now()
  }
}, { immediate: true })

// 监听思考状态变化，计算思考时间
watch(() => isThinking.value, (newIsThinking, oldIsThinking) => {
  // 思考结束：从思考状态变为非思考状态
  if (oldIsThinking && !newIsThinking && thinkingStartTime.value) {
    const endTime = Date.now()
    thinkingDuration.value = Math.round((endTime - thinkingStartTime.value) / 1000)
    thinkingStartTime.value = null
  }
})

// 处理流式输入的内容
const displayContent = computed(() => {
  if (!props.message.content) return ''

  // 移除Markdown中的图片，避免重复显示
  // 只保留文本内容，图片通过我们的自定义组件显示
  const contentWithoutImages = props.message.content.replace(/!\[.*?\]\(https?:\/\/[^\s)]+\)/g, '')

  return contentWithoutImages
})

// 方法
const formatTime = (timestamp: Date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  }).format(timestamp)
}

const copyMessage = async () => {
  try {
    await navigator.clipboard.writeText(props.message.content)
    ElMessage.success(t('aiChat.copied'))
  } catch (error) {
    console.error('Copy failed:', error)
    ElMessage.error('复制失败')
  }
}

const handleRetry = () => {
  emit('retry')
}



// 处理消息反馈
const handleFeedback = (type: 'like' | 'dislike') => {
  // 如果点击的是当前状态，则取消反馈
  if (feedbackState.value === type) {
    feedbackState.value = null
  } else {
    feedbackState.value = type
    emit('feedback', type, props.message.id || '')
    ElMessage.success(type === 'like' ? t('aiChat.feedbackLike') : t('aiChat.feedbackDislike'))
  }
}

// 为代码块添加复制按钮
const addCodeBlockCopyButtons = async () => {
  await nextTick()
  const messageElement = document.getElementById(`ai-msg-preview-${props.message.id}`)
  if (!messageElement) return

  const codeBlocks = messageElement.querySelectorAll('pre')
  codeBlocks.forEach((codeBlock) => {
    // 检查是否已经添加了复制按钮
    if (codeBlock.querySelector('.code-copy-btn')) return

    // 创建复制按钮
    const copyBtn = document.createElement('button')
    copyBtn.className = 'code-copy-btn'
    copyBtn.innerHTML = `
      <svg viewBox="0 0 1024 1024" width="14" height="14" fill="currentColor">
        <path d="M832 64H296c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h496v688c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8V96c0-17.7-14.3-32-32-32zM704 192H192c-17.7 0-32 14.3-32 32v530.7c0 8.5 3.4 16.6 9.4 22.6l173.3 173.3c2.2 2.2 4.7 4 7.4 5.5v1.9h4.4c2 0.3 4.1 0.5 6.1 0.5H704c17.7 0 32-14.3 32-32V224c0-17.7-14.3-32-32-32zM350 856.2L263.9 770H350v86.2zM672 888H414V746c0-22.1-17.9-40-40-40H232V264h440v624z"/>
      </svg>
    `
    copyBtn.title = '复制代码'

    // 添加点击事件
    copyBtn.addEventListener('click', async () => {
      const code = codeBlock.querySelector('code')?.textContent || codeBlock.textContent || ''
      try {
        await navigator.clipboard.writeText(code)
        copyBtn.innerHTML = `
          <svg viewBox="0 0 1024 1024" width="14" height="14" fill="currentColor">
            <path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2l-273 347.7-273-347.7c-6-7.7-15.3-12.2-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347.7c12.8 16.2 37.4 16.2 50.3 0l273.9-347.7c4.1-5.2 0.4-12.9-6.3-12.9z"/>
          </svg>
        `
        setTimeout(() => {
          copyBtn.innerHTML = `
            <svg viewBox="0 0 1024 1024" width="14" height="14" fill="currentColor">
              <path d="M832 64H296c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h496v688c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8V96c0-17.7-14.3-32-32-32zM704 192H192c-17.7 0-32 14.3-32 32v530.7c0 8.5 3.4 16.6 9.4 22.6l173.3 173.3c2.2 2.2 4.7 4 7.4 5.5v1.9h4.4c2 0.3 4.1 0.5 6.1 0.5H704c17.7 0 32-14.3 32-32V224c0-17.7-14.3-32-32-32zM350 856.2L263.9 770H350v86.2zM672 888H414V746c0-22.1-17.9-40-40-40H232V264h440v624z"/>
            </svg>
          `
        }, 2000)
        ElMessage.success('代码已复制')
      } catch (error) {
        console.error('复制失败:', error)
        ElMessage.error('复制失败')
      }
    })

    // 设置代码块为相对定位
    codeBlock.style.position = 'relative'
    codeBlock.appendChild(copyBtn)
  })
}

// 生命周期钩子
onMounted(() => {
  if (props.message.role === 'assistant' && props.message.content) {
    addCodeBlockCopyButtons()
  }
})

onUpdated(() => {
  if (props.message.role === 'assistant' && props.message.content) {
    addCodeBlockCopyButtons()
  }
})

// 推理相关方法
const toggleReasoning = () => {
  if (hasReasoning.value) {
    reasoningExpanded.value = !reasoningExpanded.value
  }
}

const copyReasoning = async () => {
  try {
    await navigator.clipboard.writeText(props.message.reasoning || '')
    ElMessage.success('思考过程已复制')
  } catch (error) {
    console.error('Copy reasoning failed:', error)
    ElMessage.error('复制失败')
  }
}

// 图片相关计算属性和方法
const extractedImages = computed(() => {
  if (!props.message.content) return []

  // 从Markdown内容中提取图片URL
  const imageRegex = /!\[.*?\]\((https?:\/\/[^\s)]+)\)/g
  const matches = []
  let match

  while ((match = imageRegex.exec(props.message.content)) !== null) {
    matches.push(match[1])
  }

  return matches
})

const hasImages = computed(() => {
  return extractedImages.value.length > 0
})

// 图片状态管理
const imageStatuses = ref<Map<string, ImageStatus>>(new Map())
const checkingImages = ref(false)

// 检查图片状态
const checkImageStatuses = async () => {
  const images = extractedImages.value
  if (images.length === 0) return

  checkingImages.value = true
  try {
    const statusMap = await imageStatusChecker.batchCheckStatus(images)
    imageStatuses.value = statusMap
  } catch (error) {
    console.error('检查图片状态失败:', error)
  } finally {
    checkingImages.value = false
  }
}

// 重试单个图片
const retryImage = async (imageUrl: string) => {
  try {
    const status = await imageStatusChecker.retryCheck(imageUrl)
    imageStatuses.value.set(imageUrl, status)
  } catch (error) {
    console.error('重试图片失败:', error)
  }
}

// 获取图片状态
const getImageStatus = (imageUrl: string): ImageStatus => {
  return imageStatuses.value.get(imageUrl) || { url: imageUrl, status: 'loading' }
}

// 监听图片变化，自动检查状态
watch(extractedImages, (newImages) => {
  if (newImages.length > 0) {
    // 只检查临时URL的图片
    const tempImages = newImages.filter(url => isTemporaryImageUrl(url))
    if (tempImages.length > 0) {
      checkImageStatuses()
    }
  }
}, { immediate: true })

// 下载图片
const downloadImage = async (imageUrl: string, index: number) => {
  try {
    const response = await fetch(imageUrl)
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = `generated-image-${index + 1}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    window.URL.revokeObjectURL(url)
    ElMessage.success('图片下载成功')
  } catch (error) {
    console.error('Download failed:', error)
    ElMessage.error('图片下载失败')
  }
}

// 复制图片链接
const copyImageUrl = async (imageUrl: string) => {
  try {
    await navigator.clipboard.writeText(imageUrl)
    ElMessage.success('图片链接已复制')
  } catch (error) {
    console.error('Copy failed:', error)
    ElMessage.error('复制失败')
  }
}
</script>

<style lang="scss" scoped>
.chat-message {
  width: 100%;

  &.user-message-wrapper {
    .message-content {
      justify-content: flex-end;
    }
  }

  &.ai-message-wrapper {
    .message-content {
      justify-content: flex-start;
    }
  }
}

.message-content {
  display: flex;
  gap: 12px;
  max-width: 85%;
  margin: 0 auto;
  width: 100%;

  &.user-message {
    flex-direction: row-reverse;
    margin-left: auto;
    margin-right: 0;
  }

  &.ai-message {
    margin-right: auto;
    margin-left: 0;
  }
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 16px;

  .user-message & {
    background: var(--el-color-primary);
    color: white;
  }

  .ai-message & {
    background: var(--el-color-success);
    color: white;
  }
}

.message-body {
  flex: 1;
  min-width: 0;
  max-width: calc(100% - 48px); /* 减去头像宽度和间距 */
  overflow: hidden;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
  font-size: 12px;

  .message-sender {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .message-time {
    color: var(--el-text-color-placeholder);
  }

  .message-actions {
    margin-left: auto;
    display: flex;
    gap: 4px;
  }
}

.message-text {
  padding: 6px 6px;
  border-radius: 5px;
  // line-height: 1.6;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: break-word;
  hyphens: auto;
  max-width: 100%;
  overflow-x: auto;

  .user-message & {
    background: var(--el-color-primary);
    color: white;
    border-bottom-right-radius: 4px;

    // 用户消息中的 MdPreview 样式
    .md-preview-content :deep(*) {
      color: white !important;
      background: transparent !important;
    }

    .md-preview-content :deep(code:not(pre code)) {
      background: rgba(255, 255, 255, 0.2) !important;
      border-color: rgba(255, 255, 255, 0.3) !important;
      color: white !important;
    }

    .md-preview-content :deep(pre) {
      background: rgba(0, 0, 0, 0.2) !important;
      border-color: rgba(255, 255, 255, 0.3) !important;
      color: white !important;
    }
  }

  .ai-message & {
    // background: var(--el-bg-color-page);
    color: var(--el-text-color-primary);
    border-bottom-left-radius: 4px;
    // border: 1px solid var(--el-border-color);

    /* 深色模式下使用更明显的背景 */
    html.dark & {
      background: var(--el-fill-color);
      border-color: var(--el-border-color-light);
    }

    // AI消息中的 MdPreview 确保背景透明和文字颜色
    .md-preview-content :deep(.md-editor-preview),
    .md-preview-content :deep(.md-editor-preview-wrapper),
    .md-preview-content :deep(.md-editor) {
      background: transparent !important;
      color: var(--el-text-color-primary) !important;
    }

    // AI消息中所有文字元素的颜色
    .md-preview-content :deep(*) {
      color: var(--el-text-color-primary) !important;
    }

    .md-preview-content :deep(a) {
      color: var(--el-color-primary) !important;
    }

    .md-preview-content :deep(code:not(pre code)) {
      color: var(--el-color-primary) !important;
    }

    .md-preview-content :deep(em) {
      color: var(--el-text-color-regular) !important;
    }
  }

  &.error-message {
    background: var(--el-color-error-light-9);
    border-color: var(--el-color-error-light-7);
    color: var(--el-color-error);
  }
}

// 流式输入光标样式
.streaming .md-preview-content {
  position: relative;

  // 通过伪元素实现闪烁光标
  &::after {
    content: '';
    display: inline-block;
    width: 2px;
    height: 1.2em;
    background-color: var(--el-color-primary);
    margin-left: 2px;
    animation: blink 1s infinite;
    vertical-align: text-bottom;
  }
}

.error-content {
  display: flex;
  align-items: center;
  gap: 8px;

  .error-icon {
    color: var(--el-color-error);
    flex-shrink: 0;
  }
}

.normal-content {
  // MdPreview 样式适配
  .md-preview-content {
    // 重置 MdPreview 的默认样式，使其适配消息气泡
    :deep(.md-editor-preview) {
      padding: 0 !important;
      background: transparent !important;
      border: none !important;
      font-size: inherit;
      line-height: inherit;
      color: inherit;
    }

    // 适配代码块样式
    :deep(.md-editor-preview-wrapper) {
      background: transparent !important;
      padding: 0 !important;
    }
  }
}

// 确保所有容器背景透明
.normal-content .md-preview-content {
  :deep(.md-editor) {
    background: transparent !important;
  }

  :deep(.md-editor-preview-wrapper .md-editor-preview) {
    background: transparent !important;
  }

  // 确保代码块在消息气泡中的显示效果
  :deep(pre) {
    background: var(--el-fill-color-darker) !important;
    border: 1px solid var(--el-border-color);
    border-radius: 6px;
    padding: 12px;
    margin: 8px 0;
    overflow-x: auto;
    font-size: 13px;
    line-height: 1.4;
  }

  // 行内代码样式
  :deep(code:not(pre code)) {
    background: var(--el-fill-color-light) !important;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 3px;
    padding: 2px 6px;
    font-size: 0.9em;
    color: var(--el-color-primary);
  }

  // 表格样式适配
  :deep(table) {
    border-collapse: collapse;
    width: 100%;
    margin: 12px 0;
    font-size: 13px;

    th, td {
      border: 1px solid var(--el-border-color);
      padding: 8px 12px;
      text-align: left;
    }

    th {
      background: var(--el-fill-color-light);
      font-weight: 600;
    }
  }

  // 引用块样式
  :deep(blockquote) {
    border-left: 4px solid var(--el-color-primary);
    margin: 12px 0;
    padding: 8px 16px;
    background: var(--el-fill-color-light);
    font-style: italic;
    color: var(--el-text-color-regular);
  }

  // 列表样式
  :deep(ul), :deep(ol) {
    margin: 8px 0;
    padding-left: 20px;
  }

  :deep(li) {
    margin: 4px 0;
    }

    // 标题样式
    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin: 16px 0 8px 0;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    :deep(h1) { font-size: 1.8em; border-bottom: 2px solid var(--el-border-color); padding-bottom: 8px; }
    :deep(h2) { font-size: 1.5em; border-bottom: 1px solid var(--el-border-color-light); padding-bottom: 4px; }
    :deep(h3) { font-size: 1.3em; }
    :deep(h4) { font-size: 1.1em; }
    :deep(h5) { font-size: 1.0em; }
    :deep(h6) { font-size: 0.9em; }

    // 段落样式
    :deep(p) {
      margin: 8px 0;
      line-height: 1.6;
      word-wrap: break-word;
      word-break: break-word;
      overflow-wrap: break-word;

      &:first-child {
        margin-top: 0;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }

    // 链接样式
    :deep(a) {
      color: var(--el-color-primary);
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }

    // 强调样式
    :deep(strong) {
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    :deep(em) {
      font-style: italic;
      color: var(--el-text-color-regular);
    }

    // 水平分割线
    :deep(hr) {
      border: none;
      border-top: 1px solid var(--el-border-color);
      margin: 16px 0;
    }

    // 强制覆盖所有可能的背景色设置
    :deep(*) {
      background-color: transparent !important;
    }

    // 但是代码块需要保持背景色
    :deep(pre), :deep(pre *) {
      background-color: var(--el-fill-color-darker) !important;
    }

    :deep(code:not(pre code)) {
      background-color: var(--el-fill-color-light) !important;
    }

    :deep(table th) {
      background-color: var(--el-fill-color-light) !important;
    }

    :deep(blockquote) {
      background-color: var(--el-fill-color-light) !important;
    }
  }


// 图片画廊样式
.image-gallery {
  margin-top: 12px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  max-width: 100%;

  // 响应式设计
  @media (max-width: 768px) {
    grid-template-columns: 1fr; // 移动端单列显示
    gap: 12px;
  }

  .image-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    background: var(--el-fill-color-light);
    border: 1px solid var(--el-border-color-lighter);
    max-width: 400px; // 限制最大宽度

    // 响应式最大宽度
    @media (max-width: 768px) {
      max-width: 100%;
    }

    &:hover {
      .image-actions {
        opacity: 1;
      }
    }

    .generated-image {
      width: 100%;
      height: 250px; // 调整高度
      display: block;
      cursor: pointer;

      :deep(.el-image__inner) {
        transition: transform 0.3s ease;
      }

      &:hover :deep(.el-image__inner) {
        transform: scale(1.05);
      }
    }

    .image-error {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 250px; // 与图片高度保持一致
      color: var(--el-text-color-placeholder);
      font-size: 14px;

      .el-icon {
        font-size: 32px;
        margin-bottom: 8px;
      }
    }

    .image-actions {
      position: absolute;
      top: 8px;
      right: 8px;
      display: flex;
      gap: 4px;
      opacity: 0;
      transition: opacity 0.3s ease;

      .el-button {
        background: rgba(0, 0, 0, 0.6);
        border: none;
        color: white;
        padding: 4px 8px;
        min-height: auto;

        &:hover {
          background: rgba(0, 0, 0, 0.8);
        }

        .el-icon {
          font-size: 14px;
        }
      }
    }
  }
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

// 全局 MdPreview 样式重置
.chat-message {
  // 强制重置所有 MdPreview 相关的背景和颜色
  :deep(.md-editor-preview),
  :deep(.md-editor-preview-wrapper),
  :deep(.md-editor),
  :deep(.md-editor-preview-wrapper .md-editor-preview) {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
    color: inherit !important;
  }

  // 确保所有文本元素继承父级颜色
  :deep(.md-editor-preview *) {
    color: inherit !important;
  }

  // 特殊元素的颜色处理
  :deep(.md-editor-preview a) {
    color: var(--el-color-primary) !important;
  }

  :deep(.md-editor-preview code:not(pre code)) {
    color: var(--el-color-primary) !important;
  }
}

// 深色模式适配
@media (prefers-color-scheme: dark) {
  .chat-message {
    // 深色模式下强制文字颜色
    :deep(.md-editor-preview) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(.md-editor-preview *) {
      color: inherit !important;
    }
  }

  .normal-content .md-preview-content {
    :deep(pre) {
      background: var(--el-fill-color-darker) !important;
      border-color: var(--el-border-color-dark);
      color: var(--el-text-color-primary) !important;
    }

    :deep(code:not(pre code)) {
      background: var(--el-fill-color-dark) !important;
      border-color: var(--el-border-color-dark);
      color: var(--el-color-primary) !important;
    }

    :deep(table) {
      th {
        background: var(--el-fill-color-dark);
        color: var(--el-text-color-primary) !important;
      }

      td {
        color: var(--el-text-color-primary) !important;
      }
    }

    :deep(blockquote) {
      background: var(--el-fill-color-dark);
      color: var(--el-text-color-regular) !important;
    }

    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(p) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(li) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(strong) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(em) {
      color: var(--el-text-color-regular) !important;
    }

    :deep(a) {
      color: var(--el-color-primary) !important;
    }
  }
}

// Element Plus 深色模式类适配
html.dark {
  .chat-message {
    // 深色模式下强制文字颜色
    :deep(.md-editor-preview) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(.md-editor-preview *) {
      color: inherit !important;
    }
  }

  .normal-content .md-preview-content {
    :deep(pre) {
      background: var(--el-fill-color-darker) !important;
      border-color: var(--el-border-color-dark);
      color: var(--el-text-color-primary) !important;
    }

    :deep(code:not(pre code)) {
      background: var(--el-fill-color-dark) !important;
      border-color: var(--el-border-color-dark);
      color: var(--el-color-primary) !important;
    }

    :deep(table) {
      th {
        background: var(--el-fill-color-dark);
        color: var(--el-text-color-primary) !important;
      }

      td {
        color: var(--el-text-color-primary) !important;
      }
    }

    :deep(blockquote) {
      background: var(--el-fill-color-dark);
      color: var(--el-text-color-regular) !important;
    }

    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(p) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(li) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(strong) {
      color: var(--el-text-color-primary) !important;
    }

    :deep(em) {
      color: var(--el-text-color-regular) !important;
    }

    :deep(a) {
      color: var(--el-color-primary) !important;
    }
  }
}

// 推理过程样式
.reasoning-section {
  margin-bottom: 16px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  background: var(--el-fill-color-extra-light);
  overflow: hidden;

  .reasoning-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background: var(--el-fill-color-light);
    }

    .reasoning-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      font-weight: 500;
      color: var(--el-text-color-primary);

      .thinking-icon {
        color: var(--el-color-primary);

        &.spinning {
          animation: spin 1s linear infinite;
        }
      }

      .reasoning-count {
        color: var(--el-text-color-secondary);
        font-weight: normal;
        font-size: 12px;
      }
    }

    .expand-icon {
      color: var(--el-text-color-secondary);
      transition: transform 0.3s ease;

      &.expanded {
        transform: rotate(180deg);
      }
    }
  }

  .reasoning-content {
    border-top: 1px solid var(--el-border-color-lighter);
    background: var(--el-bg-color);

    .reasoning-text {
      padding: 16px;
      font-size: 13px;
      line-height: 1.6;
      color: var(--el-text-color-regular);
      white-space: pre-wrap;
      word-break: break-word;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      background: var(--el-fill-color-blank);
      border-radius: 4px;
      margin: 12px;

      .thinking-cursor {
        color: var(--el-color-primary);
        animation: blink 1s infinite;
        font-weight: bold;
      }
    }

    .reasoning-actions {
      padding: 8px 16px 16px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

// 图片状态样式
.image-status-wrapper {
  width: 100%;

  .image-status {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 200px;
    border-radius: 8px;
    border: 1px solid var(--el-border-color-light);

    &.checking {
      background: var(--el-fill-color-extra-light);
      color: var(--el-text-color-regular);
      gap: 8px;

      .loading-icon {
        animation: spin 1s linear infinite;
        color: var(--el-color-primary);
      }
    }

    &.expired {
      background: var(--el-color-warning-light-9);
      border-color: var(--el-color-warning-light-5);
    }

    &.error {
      background: var(--el-color-danger-light-9);
      border-color: var(--el-color-danger-light-5);
    }
  }

  .expired-placeholder,
  .error-placeholder {
    text-align: center;
    padding: 20px;

    .expired-icon,
    .error-icon {
      font-size: 48px;
      margin-bottom: 12px;

      &.expired-icon {
        color: var(--el-color-warning);
      }

      &.error-icon {
        color: var(--el-color-danger);
      }
    }

    .expired-text,
    .error-text {
      margin-bottom: 16px;

      p {
        margin: 0;

        &:first-child {
          font-size: 16px;
          font-weight: 500;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }
      }

      .expired-hint,
      .error-hint {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        line-height: 1.4;
      }
    }

    .retry-btn {
      margin-top: 8px;
    }
  }
}

// 动画
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 消息反馈按钮样式
.message-feedback {
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px solid var(--el-border-color-lighter);

  .feedback-buttons {
    display: flex;
    gap: 8px;
    justify-content: flex-start;

    .feedback-btn {
      padding: 4px 8px;
      min-height: auto;
      border-radius: 6px;
      transition: all 0.3s ease;

      &:hover {
        transform: scale(1.1);
      }

      .el-icon {
        font-size: 16px;
      }
    }
  }
}



// 代码块复制按钮样式
:deep(.code-copy-btn) {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.6);
  border: none;
  border-radius: 4px;
  color: white;
  padding: 6px 8px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 10;

  &:hover {
    background: rgba(0, 0, 0, 0.8);
  }

  svg {
    display: block;
  }
}

:deep(pre:hover .code-copy-btn) {
  opacity: 1;
}

// 深色模式适配
html.dark {
  .message-feedback {
    border-top-color: var(--el-border-color-dark);
  }

  :deep(.code-copy-btn) {
    background: rgba(255, 255, 255, 0.1);
    color: var(--el-text-color-primary);

    &:hover {
      background: rgba(255, 255, 255, 0.2);
    }
  }
}

// 思考动画
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 光标闪烁动画
@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .message-content {
    max-width: 95%;
  }

  .message-avatar {
    width: 32px;
    height: 32px;
    font-size: 14px;
  }

  .message-text {
    padding: 10px 12px;
    font-size: 14px;
  }

  .message-header {
    font-size: 11px;
  }
}
</style>
